<template>
  <div class="hospital-management">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-form :model="searchForm" inline>
        <el-form-item label="医院名称">
          <el-input
            v-model="searchForm.hospitalName"
            placeholder="请输入医院名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="所在地区">
          <el-cascader
            v-model="searchForm.location"
            :options="regionOptions"
            :props="{
              expandTrigger: 'hover',
              value: 'value',
              label: 'label',
              children: 'children'
            }"
            placeholder="请选择省/市"
            clearable
          />
        </el-form-item>

        <el-form-item label="是否推荐">
          <el-select
            v-model="searchForm.isRecommended"
            placeholder="请选择"
            clearable
          >
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="医院科室">
          <el-select
            v-model="searchForm.hospitalDepartments"
            multiple
            collapse-tags
            placeholder="请选择科室"
            clearable
          >
            <el-option-group label="内科">
              <el-option
                v-for="dept in internalDepartments"
                :key="dept"
                :label="dept"
                :value="dept"
              />
            </el-option-group>
            <el-option-group label="外科">
              <el-option
                v-for="dept in surgeryDepartments"
                :key="dept"
                :label="dept"
                :value="dept"
              />
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 医院列表 -->
    <div class="hospital-list">
      <div class="list-header">
        <el-button type="primary" @click="handleAdd">新增医院</el-button>
      </div>

      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="hospitalName" label="医院名称" />
        <el-table-column label="医院图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.hospitalPicture"
              :src="row.hospitalPicture"
              :preview-src-list="[row.hospitalPicture]"
              fit="cover"
              class="hospital-image"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="是否推荐" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isRecommended === 1 ? 'success' : 'info'">
              {{ row.isRecommended === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="doctorCount" label="医生人数" width="100" />
        <el-table-column prop="departmentquantity" label="科室数" width="100" />
        <el-table-column
          prop="hospitalDepartments"
          label="医院科室"
          show-overflow-tooltip
        />
        <el-table-column
          prop="location"
          label="所在地区"
          show-overflow-tooltip
        />
        <el-table-column prop="hospitalPhone" label="医院电话" width="120" />
        <el-table-column prop="createName" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button type="success" link @click="handleDetail(row)"
              >详情</el-button
            >
            <el-button type="danger" link @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部操作栏 -->
      <div class="footer-toolbar">
        <el-checkbox v-model="selectAll" @change="handleSelectAll"
          >全选</el-checkbox
        >
        <el-button
          type="danger"
          :disabled="!selectedHospitals.length"
          @click="batchDelete"
        >
          批量删除
        </el-button>

        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { provinceAndCityData } from 'element-china-area-data';
import axios from 'axios';

const router = useRouter();
const tableRef = ref();

// 科室选项
const internalDepartments = ['心内科', '消化内科', '内分泌科'];
const surgeryDepartments = ['神经外科', '胸外科', '泌尿外科'];

// 地区选项
const regionOptions = provinceAndCityData;

// 搜索表单
const searchForm = reactive({
  hospitalName: '',
  location: [],
  isRecommended: '',
  hospitalDepartments: []
});

// 表格数据
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 多选相关
const selectedHospitals = ref([]);
const selectAll = ref(false);

// 获取医院列表
const fetchHospitalList = async () => {
  try {
    // 处理查询参数
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      hospitalName: searchForm.hospitalName,
      isRecommended: searchForm.isRecommended,
      hospitalDepartments: searchForm.hospitalDepartments.join(','),
      location: searchForm.location.join('-')
    };

    const res = await axios.get(
      'http://localhost:5223/api/Hospitail/HospitalQuery',
      { params }
    );

    if (res.data.code === 210) {
      tableData.value = res.data.data.list;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取医院列表失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchHospitalList();
};

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach((key) => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = [];
    } else {
      searchForm[key] = '';
    }
  });
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchHospitalList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchHospitalList();
};

// 多选处理
const handleSelectionChange = (selection) => {
  selectedHospitals.value = selection;
  selectAll.value = selection.length === tableData.value.length;
};

const handleSelectAll = (value) => {
  if (value) {
    tableData.value.forEach((row) => {
      tableRef.value.toggleRowSelection(row, true);
    });
  } else {
    tableRef.value.clearSelection();
  }
};

// 新增医院
const handleAdd = () => {
  router.push('/HospitalManagementCreate');
};

// 编辑医院
const handleEdit = (row) => {
  router.push({
    path: '/HospitalManagementUpdate',
    query: { hospitalId: row.hospitalId }
  });
};

// 查看详情
const handleDetail = (row) => {
  router.push({
    path: '/HospitalManagementInfo',
    query: { hospitalId: row.hospitalId }
  });
};

// 删除医院
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该医院吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await axios.post(
          'http://localhost:5260/api/HospitalZ/HospitalDelete',
          {
            hospitalId: row.hospitalId
          }
        );
        if (res.data.code === 204) {
          ElMessage.success('删除成功');
          fetchHospitalList();
        } else {
          ElMessage.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除医院失败:', error);
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {});
};

// 批量删除
const batchDelete = () => {
  if (selectedHospitals.value.length === 0) {
    ElMessage.warning('请选择要删除的医院');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedHospitals.value.length} 家医院吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 由于没有批量删除接口，这里使用循环调用单个删除接口
        const deletePromises = selectedHospitals.value.map((hospital) =>
          axios.post('http://localhost:5260/api/HospitalZ/HospitalDelete', {
            hospitalId: hospital.hospitalId
          })
        );

        const results = await Promise.all(deletePromises);
        const allSuccess = results.every((res) => res.data.code === 204);

        if (allSuccess) {
          ElMessage.success('批量删除成功');
          fetchHospitalList();
        } else {
          ElMessage.error('部分删除失败');
        }
      } catch (error) {
        console.error('批量删除失败:', error);
        ElMessage.error('批量删除失败');
      }
    })
    .catch(() => {});
};

// 初始化
onMounted(() => {
  fetchHospitalList();
});
</script>

<style scoped>
.hospital-management {
  padding: 20px;
  background: #fff;
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.hospital-list {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.list-header {
  margin-bottom: 20px;
}

.footer-toolbar {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.pagination {
  margin-left: auto;
}

.hospital-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
}

:deep(.el-select) {
  width: 200px;
}

:deep(.el-cascader) {
  width: 200px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 20px;
}
</style>
